const Actions = require('./actions');
const DB = require('app/db.js');
import { guid,getTime, getMarkdownText,sendNotice} from 'clientConfig/util/queryurlfield';
const monStorage = require('clientConfig/util/StoreData').monStorage;
const Storage = require('clientConfig/util/StoreData').Storage;
import { Control } from 'react-keeper';
const { Toast } = SaltUI;

let form_component_values = null
let upfileName = []
module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {
        loaded: false
    },

    onFetch: function(params, cb) {
        let t = this;
        upfileName = [];
        DB.Approval.get_approval_list({
            proj_category: "payreq",
            status: 2,
            PageNum: 0,
            CountForAPage: 100,
            id: Storage.get('user.id')
        }).then((content) => {// 成功
            var payProportionAll = [];
            var payMoneyAll = []; //支付金额
            var paypointeAll = [];
            var proNameAll = [];
            var prosnameCheck = [];
            var proNumAll = [];
            var process_id = [];
            var folder_id = [];
            var webhookAll = [];
            var perdeductionsAll = [];
            var deductionsMoneyAll = [];
            var paymanage_proportion = null;
            var Perdeductions = null;
            content.list.map((item, index)=>{
                try{
                    Perdeductions = JSON.parse(item["Perdeductions"]);
                    paymanage_proportion = JSON.parse(item['paymanage_proportion'])
                }catch(e){
                    Perdeductions = item["Perdeductions"]
                    paymanage_proportion = item['paymanage_proportion']
                }
                if(prosnameCheck.indexOf(item['proj_name']) != -1){
                    var indexNum = prosnameCheck.indexOf(item['proj_name']); 
                    paypointeAll[indexNum].push({value: 1, text: item['paymanage_node']})
                    payProportionAll[indexNum].push(paymanage_proportion["payProportion"])//支付金额数组
                    payMoneyAll[indexNum].push(paymanage_proportion["payMoney"])
                    perdeductionsAll[indexNum].push(Perdeductions["Perdeductions"])
                    deductionsMoneyAll[indexNum].push(Perdeductions["deductionsMoney"])
                }else{
                    prosnameCheck.push(item["proj_name"])
                    proNameAll.push({value: index, text: item["proj_name"]})
                    process_id.push(item.process_id)
                    folder_id.push(item.folder_id)
                    proNumAll.push(item["proj_num"])
                    webhookAll.push(item.proj_webhook)
                    paypointeAll.push([{value: 0, text: item['paymanage_node']}])
                    payProportionAll.push([paymanage_proportion["payProportion"]])
                    payMoneyAll.push([paymanage_proportion["payMoney"]])
                    perdeductionsAll.push([Perdeductions["Perdeductions"]])
                    deductionsMoneyAll.push([Perdeductions["deductionsMoney"]])

                }
            })
            t.data.payProportionAll = payProportionAll;
            t.data.payMoneyAll = payMoneyAll;
            t.data.paypointeAll = paypointeAll;
            t.data.proNameAll = proNameAll;
            t.data.proNumAll = proNumAll;
            t.data.process_id = process_id;
            t.data.folder_id = folder_id;
            t.data.webhookAll = webhookAll;
            t.data.perdeductionsAll = perdeductionsAll;
            t.data.deductionsMoneyAll = deductionsMoneyAll;
            t.data.upfileName = [];
            t.updateComponent();
        }).catch((error) => { // 失败 or 有异常被捕获
           
        });
    },
    onCheck: function (params,pointer) {//判断支付节点的支付申请是否提交,提交过支付申请的支付节点不在显示
        let t = this;
        DB.Approval.get_approval_list({
            proj_category: "paytransfer",
            proj_name: params,
            PageNum: 0,
            CountForAPage: 10
        }).then((content) => {
            var paymanage_nodeAll = []
            if(content.list instanceof Array){
                content.list.map((item,index)=>{
                    paymanage_nodeAll.push(item.paymanage_node);
                })
            }else{
                paymanage_nodeAll.push(content.list.paymanage_node);
            }
            t.data.paymanage_nodeAll = paymanage_nodeAll;
            for(var i = 0; i < t.data.paymanage_nodeAll.length; i++){  
                for(var j = 0; j < pointer.length; j++){  
                    if(pointer[j].text == t.data.paymanage_nodeAll[i]){
                        pointer.splice(j,1);
                    }  
                }  
            }
            if(pointer.length == 0){
                Toast.show({
                    type: 'error',
                    content: "该项目的所有支付节点的支付流转都已提交",
                    duration: 2888
                })
            }
            t.data.paypointeCurr = pointer
            t.updateComponent();
        })
    },
    onSendForm: function (params,contents ,boo) {
        let t = this;
        let agent_id = Storage.get('user.agentid');
        let create_time = getTime();
        let finish_time = "";
        let originator_user = monStorage.get('user.nickname');
        let originator_user_id = Storage.get('user.id') //审批发起人的userid
        let dept_id = monStorage.get('user.department');
        let approvers = contents.spr;
        let approvers_id = contents.approvers_id;
        let cc_list = contents.csr;
        let cc_list_id = contents.cc_list_id;
        let folder_id = contents.folder_id;
        var array = [];
        if(approvers instanceof Array){
            for (let i = 0; i < approvers.length; i++) {
                array.push(JSON.stringify({ content: "", file: "", imgae: "" }));
            }
        }
        let process_result = array.length > 1 ? array : JSON.stringify({ content: "", file: "", imgae: "" });
        let next_cursor = 0;
        const status = 1;
        const module_type = "payment";
        const proj_category = !boo ? "paytransfer" : "changereq";
        const proj_num = contents.proNum;
        const proj_name = params.data.payplan;
        const proj_webhook = contents.proj_webhook;  
        const proj_markdown = getMarkdownText({create_time, originator_user, approvers, proj_name, proj_num, status,title:"支付流转"})
        const process_id = guid();
        var nodelists = []
        let node_info = [];
        for(let i=0; i<params.node.length;i++){
            var obj = {}
            obj.name = params.node[i].label;
            obj.value = params.data[params.node[i].name];
            node_info.push(obj);
        }
        var obj = {}
        node_info.push({name:'上传附件',value:contents.upfileName})
        obj.node_info = node_info
        Object.assign(obj,{node_name: !boo ? "paytransfer" : "changereq",modified:!boo ? "0" : '1' ,permission:"1"})
        nodelists.push(obj);
        form_component_values = {
            content:{paymanage_node: params.data.paypointer ,payplanId: contents.payplanId},
            nodelists: nodelists
        }
        var send = Object.assign({}, {agent_id, create_time, finish_time, originator_user, originator_user_id, dept_id, folder_id,approvers, approvers_id, cc_list, cc_list_id, process_result, next_cursor, status, module_type, proj_category, proj_num, proj_name, proj_webhook, proj_markdown, process_id, form_component_values})
        //console.log(send)
        if (params.pagedata) {
            send = this.modify(send, params);
        }
        let notice_info = {
            "process_id": process_id,
            "proj_num": proj_num,
            "proj_name": proj_name,
            "create_time": create_time,
            "status": status,
            "type":"待我审批的"
        }
        let noticed_lists = approvers_id instanceof  Array ? approvers_id[next_cursor] : approvers_id;
        DB.Approval.send_approval(send)
        .then((content) => { // 成功
            Toast.show({
                type: 'success',
                content: '你的支付流转已提交'
            });
            sendNotice(noticed_lists, notice_info)
            Control.go(-1)
        })
        .catch((error) => { // 失败 or 有异常被捕获
            if(error.message){
                Toast.show({
                    type: 'error',
                    content: error.message
                });
            }else{
                Toast.show({
                    type: 'error',
                    content: '提交失败'
                });
            }
        });
    },
    modify: function (new_data, old_data) {
        let edit = old_data.edit;
        old_data = old_data.pagedata;
        let old_change = [];//变更前字段 发送群消息
        let new_change = [];//变更后字段 发送群消息
        let form_component_values_new = new_data.form_component_values;
        let nodelists_new = form_component_values_new.nodelists;
        for (let i = 0; i < nodelists_new.length; i++) {
            let node_info_new = nodelists_new[i].node_info;
            let node_info_old = old_data.node_info;
            for (let j = 0; j < node_info_new.length; j++) {
                if (node_info_new[j].value != node_info_old[j].value) {
                    node_info_new[j].ext_value = node_info_old[j].value//变更过
                    old_change.push(node_info_old[j].value);
                    new_change.push(node_info_new[j].value);
                }
            }
        }
        form_component_values_new.nodelists = nodelists_new;
        form_component_values_new.content.changerecord_type = JSON.stringify({
            type: edit ? "撤销申请" : "内容变更",
            old_process_id: old_data.process_id
        })
        new_data.form_component_values = form_component_values_new;
        let { create_time, originator_user, approvers, approvers_id, next_cursor, proj_name, proj_num, status } = { ...new_data };
        const proj_markdown = getMarkdownText({ old_change, new_change, change_type: edit ? "撤销申请" : "内容变更", create_time, originator_user, approvers: approvers[next_cursor], proj_name, proj_num, status,title: '支付管理' }, "change")
        new_data.proj_markdown = proj_markdown;
        return new_data;
    },
    onUpFiles: function(params,data,ele) {
        let t = this
        ele.style.opacity = 1
        $.ajax({
            type: "post",
            url: "/its/upload_file?proj_name=" + params.name + "&file_uper=" + monStorage.get('user.nickname'),
            data: data,
            processData: false,
            contentType: false,
            beforeSend: function () {
                ele.style.width = "50%"          
            },
            success: function (result){
                ele.style.width = "100%"   
                setTimeout(function () {
                    ele.style.opacity = 0   
                }, 700);
                setTimeout(function () {
                    ele.style.width = 0  
                }, 1000);
                upfileName.push({fileName:result.content.file_name,fileId:result.content.file_id})
                t.data.upfileName = upfileName
                t.updateComponent()
            }
        })
    },
    onDelFiles: function(id){
        let t = this
        DB.File.delete_file({
            file_id:id,
            id:Storage.get('user.id')
        })
        .then((content) => { // 成功
            for(var i=0;i<upfileName.length;i++){
                if(upfileName[i].fileId == id){
                    upfileName.splice(i,1)
                }
            }
            t.data.upfileName = upfileName
            t.updateComponent()
        })
        .catch((error) => { // 失败 or 有异常被捕获
            
        });
    },
    updateComponent: function() {
        this.trigger(this.data);
    },

    getInitialState: function() {
        return this.data;
    }
});
